<template>
  <div class="channel-edit">
    <van-cell :border="false">
      <div slot="title" class="title-text">我的频道</div>
      <van-button
        type="danger"
        plain
        round
        size="mini"
        class="edit-btn"
        @click="isEdit = !isEdit"
        >{{ isEdit ? '完成' : '编辑' }}</van-button
      >
    </van-cell>
    <van-grid :gutter="10" class="my-grid">
      <van-grid-item
        v-for="(channel, index) in myChannels"
        :key="index"
        class="grid-item"
        @click="onMyChannelClick(channel, index)"
      >
        <van-icon
          name="clear"
          slot="icon"
          v-show="isEdit && !fiexChannels.includes(channel.id)"
        >
        </van-icon>

        <span slot="text" class="text" :class="{ active: index === active }"
          >{{ channel.name }}
        </span>
      </van-grid-item>
    </van-grid>

    <!-- 频道推荐 -->
    <van-cell :border="false">
      <div slot="title" class="title-text">推荐频道</div>
    </van-cell>
    <van-grid :gutter="10" class="recommend-grid">
      <van-grid-item
        v-for="(channel, index) in recommendChannels"
        :key="index"
        icon="plus"
        :text="channel.name"
        class="grid-item"
        @click="onAddChannel(channel)"
      ></van-grid-item>
    </van-grid>
    <!-- /频道推荐 -->
  </div>
</template>
<script>
import {
  getAllChannels,
  addUserChannel,
  deleteUserChannel,
} from '@/api/channel'
import { mapState } from 'vuex'
import { setItem } from '@/utils/storage'
export default {
  name: 'channel-edit',
  props: {
    myChannels: {
      type: Array,
      required: true,
    },
    active: {
      type: Number,
      required: true,
    },
  },
  data() {
    return {
      allChannels: [], //所有频道
      isEdit: false, //控制所有按钮隐藏和显示
      fiexChannels: [0],
    }
  },
  computed: {
    ...mapState(['user']),
    // 计算属性会观测内部依赖数据的变化
    // 如果依赖的数据发生变化，则计算属性会重新执行
    recommendChannels() {
      // 数组的 filter 方法：遍历数组，把符合条件的元素存储到新数组中并返回
      return this.allChannels.filter((channel) => {
        // const channels = []

        // 数组的 find 方法：遍历数组，把符合条件的第1个元素返回
        return !this.myChannels.find((myChannel) => {
          return myChannel.id === channel.id
        })

        // return channels
      })
    },
    // recommendChannels () {
    //   const channels = []
    //   this.allChannels.forEach(channel => {
    //     // find 遍历数组，找到满足条件的元素项
    //     const ret = this.myChannels.find(myChannel => {
    //       return myChannel.id === channel.id
    //     })

    //     // 如果我的频道中不包括该频道项，则收集到推荐频道中
    //     if (!ret) {
    //       channels.push(channel)
    //     }
    //   })

    //   // 把计算结果返回
    //   return channels
    // }
  },
  components: {},
  watch: {},
  mounted() {},
  created() {
    this.loadAllChannels()
  },

  methods: {
    async loadAllChannels() {
      try {
        const { data } = await getAllChannels()
        // console.log(data)
        this.allChannels = data.data.channels
        console.log(this.allChannels)
      } catch (err) {
        this.$toast('数据获取失败')
      }
    },
    async onAddChannel(channel) {
      this.myChannels.push(channel)

      // 数据持久化处理
      if (this.user) {
        try {
          // 已登录，把数据请求接口放到线上
          await addUserChannel({
            id: channel.id, // 频道ID
            seq: this.myChannels.length, // 序号
          })
        } catch (err) {
          this.$toast('保存失败，请稍后重试')
        }
      } else {
        // 未登录，把数据存储到本地
        setItem('TOUTIAO_CHANNELS', this.myChannels)
      }
    },

    onMyChannelClick(channel, index) {
      if (this.isEdit) {
        //   1.如果是固定频道，则不删除
        if (this.fiexChannels.includes(channel.id)) {
          return
        }
        this.myChannels.splice(index, 1)
        //   3.如果删除的频道是激活之前的频道，则更新激活的频道项
        // 参数1：要删除的元素索引
        // 参数2：要删除的个数，如果不指定，则从参数1开始一直删除到最后

        if (index <= this.active) {
          this.$emit('update-active', this.active - 1, true)
        }
        // 处理数据持久化
        this.deleteChannel(channel)
      } else {
        //   非编辑状态，执行切换频道
        this.$emit('update-active', index, false)
      }
    },
    async deleteChannel(channel) {
      try {
        if (this.user) {
          // 已登录，则将数据更新到线上
          await deleteUserChannel(channel.id)
        } else {
          // 未登录，将数据更新到本地
          setItem('TOUTIAO_CHANNELS', this.myChannels)
        }
      } catch (err) {
        this.$toast('操作失败请稍后重试')
      }
    },
  },
}
</script>
<style lang="less" scoped>
.channel-edit {
  padding: 85px 0;
}

.title-text {
  font-size: 32px;
  color: #333;
}

.edit-btn {
  width: 104px;
  height: 48px;
  font-size: 26px;
  color: #f85959;
  border: 1px solid #f85959;
}
/deep/ .grid-item {
  width: 160px;
  height: 86px;

  .van-grid-item__content {
    //   文字不换行
    white-space: nowrap;
    background-color: #dbd9d9;
    .van-grid-item__text,
    .text {
      font-size: 28px;
      color: #333;
      margin-top: 0;
    }
    .active {
      color: red;
    }
  }
  .van-grid-item__icon-wrapper {
    position: unset;
  }
}

/deep/ .my-grid {
  .grid-item {
    .van-icon-clear {
      position: absolute;
      right: -10px;
      top: -10px;
      color: #cacaca;
      font-size: 30px;
      z-index: 2;
    }
  }
}

/deep/ .recommend-grid {
  .grid-item {
    .van-grid-item__content {
      // flex-direction: row;
      flex-direction: row;
      .van-icon-plus {
        font-size: 28px;
        margin-right: 6px;
      }
    }
  }
}
</style>
